﻿using UnityEngine;
using System.Collections;

public class AlphaOverLifetime : MonoBehaviour
{

	public float time;
	public bool isSprite;
	public bool isInverse;
    public bool isGUIText;
	public float inverseTarget;

	private float amount;
	private float i;
	private SpriteRenderer targetSpriteRenderer;
	void Start ()
	{
		if (isSprite) 
		{
			targetSpriteRenderer = GetComponent<SpriteRenderer> ();
			amount = (-targetSpriteRenderer.color.a / time) * Time.deltaTime;
			i = targetSpriteRenderer.color.a;
		}
        else if (!isGUIText)
        {
            amount = (-renderer.material.color.a / time) * Time.deltaTime;
            i = renderer.material.color.a;
        }
        else
        {
            amount = (-guiText.color.a / time) * Time.deltaTime;
            i = guiText.color.a;
        }

		if (isInverse)
		{
			amount = (inverseTarget/time)*Time.deltaTime;

		}
	}

	void Update ()
	{
		i += amount;

		if (targetSpriteRenderer != null) 
		{
			targetSpriteRenderer.color = new Color(targetSpriteRenderer.color.r,targetSpriteRenderer.color.g,targetSpriteRenderer.color.b,i);
		}
        else if (!isGUIText)
        {
            renderer.material.color = new Color(renderer.material.color.r, renderer.material.color.g, renderer.material.color.b, i);
        }
        else
        {
            guiText.color = new Color(guiText.color.r, guiText.color.g, guiText.color.b, i);
        }

		if (isInverse) 
		{
			if (i >= inverseTarget) 
			{
				if (isSprite) 
				{
					amount = (-targetSpriteRenderer.color.a / time) * Time.deltaTime;
					i = targetSpriteRenderer.color.a;
				}
				else
				{
					amount = (-renderer.material.color.a/time)*Time.deltaTime;
				}
				isInverse = false;
			}
		}
		else
		{
			if (i <= 0) 
			{
				Destroy (gameObject);
			}
		}
	}
}